#include <errno.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <libusb.h>

struct libusb_device_handle *devh = NULL;

static int find_dpfp_device(void)
{
    devh = libusb_open_device_with_vid_pid(NULL, 0x045e, 0x02b0);
    return devh ? 0 : -EIO;
}


int main(void)
{

    int r = 1;

    printf("Step 0\n");
    r = libusb_init(NULL);
    if (r < 0) {
	fprintf(stderr, "failed to initialise libusb\n");
	exit(1);
    }

    printf("Step 1\n");
    r = find_dpfp_device();
    if (r < 0) {
	fprintf(stderr, "Could not find/open device\n");
	exit(1);
    }

    printf("Step 2\n");
    r = libusb_claim_interface(devh, 0);
    if (r < 0) {
	fprintf(stderr, "usb_claim_interface error %d\n", r);
	printf("Step 2 exit");
	exit(0);
    }

    int k;
    static const char filename[] = "/proc/kinect_proc";	//replace with /proc filename
    char *previous_command = malloc(10 * sizeof(char));
    unsigned char *a = malloc(20);

    while (1) {			/* read a line */
	// printf("opening file\n"); 
	FILE *file = fopen(filename, "r");

	if (file != NULL) {

	    char line[10];	/* or other suitable maximum line size */
	    if (fgets(line, 10, file) != NULL) {
		if (0 != strncmp(previous_command, line, 10)) {
		    if (0 == strncmp("up", line, 2)) {	//move motor up
			printf("UP\n");
			k = libusb_control_transfer(devh, 0x40, 0x31,
						    0xffd0, 1, a, 1, 0);
		    }
		    if (0 == strncmp("down", line, 4)) {	//move motor down
			printf("Down\n");
			k = libusb_control_transfer(devh, 0x40, 0x31,
						    0xfff0, 1, a, 1, 0);
		    }
		    if (0 == strncmp("right", line, 4)) {	//stop blinking &changes to yellow
			printf("right\n");
			k = libusb_control_transfer(devh, 0x40, 0x6, 0x1,
						    1, a, 1, 0);
			k = libusb_control_transfer(devh, 0x40, 0x6, 0x3,
						    1, a, 1, 0);
		    }
		    if (0 == strncmp("left", line, 4)) {	//start blinking
			printf("Left\n");
			k = libusb_control_transfer(devh, 0x40, 0x6, 0x4,
						    1, a, 1, 0);
			k = libusb_control_transfer(devh, 0x40, 0x6, 0x2,
						    1, a, 1, 0);
		    }
		    strncpy(previous_command, line, 10);
		}
	    } else {
		perror(filename);	/* why didn't the file open? */
	    }
	}
	fclose(file);
    }
    free(a);
    free(previous_command);
    return 0;
}
